package util

import (
	"errors"
	"net"
	"os"
)

var ErrLocalIPCanNotBeFoundByHostsFile = errors.New("local ip can not be found by hosts file")
var ErrLocalIPCanNotBeFoundByNetInterface = errors.New("local ip can not be found by net interface")

func LocalIPByHostsFile() (string, error) {
	name, err := os.Hostname()
	if err != nil {
		return "", err
	}

	addr, err := net.LookupHost(name)
	if err != nil {
		return "", err
	}

	if len(addr) == 0 {
		return "", ErrLocalIPCanNotBeFoundByHostsFile
	}

	return addr[0], nil
}

func LocalIPByNetInterface() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}

	for _, address := range addrs {
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String(), nil
			}
		}
	}

	return "", ErrLocalIPCanNotBeFoundByNetInterface
}
